package com.example.jin.myplayer.myApplication;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.media.AudioManager;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SimpleAdapter;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.example.jin.myplayer.R;
import com.example.jin.myplayer.data.Music;
import com.example.jin.myplayer.data.MusicList;
import com.example.jin.myplayer.data.PropertyBean;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

public class MyPlayer extends AppCompatActivity implements GestureDetector.OnGestureListener{
    //显示组件
    private ImageButton imgBtn_Previous;
    private ImageButton imgBtn_Pause;
    private ImageButton imgBtn_Stop;
    private ImageButton imgBtn_Next;
    private ListView listView;
    private RelativeLayout rootLayout;
    private TextView text_Current;
    private TextView text_Duration;
    private TextView textView;
    private SeekBar seekBar;
    private Handler seekBarHandler;


    //歌曲列表对象
    private ArrayList<Music> musicArrayList;
    //退出判断标记
    private static boolean isExit = false;
    //当前歌曲的序号
    private int number = 0;
    //播放状态
    private int status;
    //广播接收器
    private StatusChangReceiver receiver;
    //当前歌曲的持续时间和当前时间
    private int duration;
    private int time;
    //进度条控制常量
    private final static int PROGRESS_INCREASE = 0;
    private final static int PROGRESS_PAUSE = 1;
    private final static int PROGRESS_RESET = 2;
    //播放模式
    private final static int MODE_LIST_SEQUENCE = 0;
    private final static int MODE_SINGLE_CYCLE = 1;
    private final static int MODE_LIST_CYCLE = 2;
    private int playmode;
    //音乐控制
    private TextView tv_vol;
    private SeekBar seekBar_vol;
    //睡眠模式相关组件，标识常量
    private ImageView iv_sleep;
    private Timer timer_sleep;
    private static final boolean NOTSLEEP = false;
    private static final boolean ISTSLEEP = true;
    //默认睡眠时间
    private int sleep_minute = 20;
    //标记是否打开睡眠模式
    private static boolean sleepmode;
    //手势识别对象
    private GestureDetector gestureDetector;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        findViews();
        registerListener();
        initMusicList();
        initListView();
        checkMusicfile();

        duration = 0;
        time = 0;

        //绑定广播接收器
        bindStatusChangedReceiver();

        initseekBarHandler();
        startService(new Intent(this, MusicService.class));
        status = MusicService.COMMAND_STOP;
        //默认播放模式:顺序播放
        playmode = MyPlayer.MODE_LIST_SEQUENCE;
        //默认睡眠模式为关闭状态
        sleepmode = MyPlayer.NOTSLEEP;
        gestureDetector = new GestureDetector(this, this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        sendBroadcastOnCommand(MusicService.COMMAND_CHECK_IS_PLAYING);
        PropertyBean propertyBean = new PropertyBean(MyPlayer.this);
        String theme = propertyBean.getTheme();
        setTheme(theme);
        audio_Control();
        //睡眠模式打开时显示图标，否则隐藏
        if(sleepmode == MyPlayer.ISTSLEEP){
            iv_sleep.setVisibility(View.VISIBLE);
        }else{
            iv_sleep.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    protected void onDestroy() {
        if (status == MusicService.STATUS_STOPED) {
            stopService(new Intent(this, MusicService.class));
        }
        super.onDestroy();
    }

    /**绑定广播接收器*/
    private void bindStatusChangedReceiver() {
        receiver = new StatusChangReceiver();
        IntentFilter filter = new IntentFilter(MusicService.BROADCAST_MUSICSERVICE_UDDATE_STATUS);
        registerReceiver(receiver, filter);
    }

    /**获取组件*/
    private void findViews(){
        imgBtn_Previous = (ImageButton) findViewById(R.id.imageButton);
        imgBtn_Pause = (ImageButton) findViewById(R.id.imageButton2);
        imgBtn_Stop = (ImageButton) findViewById(R.id.imageButton3);
        imgBtn_Next = (ImageButton) findViewById(R.id.imageButton4);
        listView = (ListView) findViewById(R.id.listview1);
        rootLayout = (RelativeLayout) findViewById(R.id.relativelayout);
        text_Current = (TextView) findViewById(R.id.textView);
        text_Duration = (TextView) findViewById(R.id.textView2);
        seekBar = (SeekBar) findViewById(R.id.seekBar2);
        textView = (TextView) findViewById(R.id.textView3);

        tv_vol = (TextView)  findViewById(R.id.main_tv_volumeText);
        seekBar_vol = (SeekBar) findViewById(R.id.main_sb_volumeBar);

        iv_sleep = (ImageView) findViewById(R.id.iv_sleep);
    }

    /**注册监听器*/
    private void registerListener(){
        imgBtn_Previous.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendBroadcastOnCommand(MusicService.COMMAND_PREVIOUS);
            }
        });
        imgBtn_Pause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (status){
                    case MusicService.STATUS_PLAYING :
                        sendBroadcastOnCommand(MusicService.COMMAND_PAUSE);
                        break;
                    case MusicService.COMMAND_PAUSE :
                        sendBroadcastOnCommand(MusicService.COMMAND_RESUME);
                        break;
                    case MusicService.COMMAND_STOP :
                        sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
                        break;
                    default:
                        break;
                }
            }
        });
        imgBtn_Stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendBroadcastOnCommand(MusicService.COMMAND_STOP);
            }
        });
        imgBtn_Next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(playmode == MyPlayer.MODE_LIST_CYCLE){
                    if ((number ) == MusicList.getMusicList().size()-1) {
                        number = 0;
                        sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
                    } else {
                        sendBroadcastOnCommand(MusicService.COMMAND_NEXT);
                    }
                }else  sendBroadcastOnCommand(MusicService.COMMAND_NEXT);
            }
        });
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                number = position;
                sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
            }
        });
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if(status != MusicService.STATUS_STOPED){
                    time = seekBar.getProgress();
                    //更新文本
                    text_Current.setText(formatTime(time));
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                //进度条暂停
                seekBarHandler.sendEmptyMessage(PROGRESS_PAUSE);
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if(status != MusicService.STATUS_STOPED){
                    time = seekBar.getProgress();
                    //更新文本
                    text_Current.setText(formatTime(time));
                    //发送广播给MusicService，执行跳转
                    sendBroadcastOnCommand(MusicService.COMMAND_SEEK_TO);
                }
                if(status == MusicService.STATUS_PLAYING){
                    sendBroadcastOnCommand(MusicService.COMMAND_SEEK_TO);
                    //进度条恢复移动
                    seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE, 1000);
                }
                if(status == MusicService.STATUS_PAUSED){
                    sendBroadcastOnCommand(MusicService.COMMAND_SEEK_TO);
                    sendBroadcastOnCommand(MusicService.COMMAND_RESUME);
                    seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE, 1000);
                }
            }
        });
    }

    /**初始化音乐列表对象*/
    private void initMusicList(){
        musicArrayList = MusicList.getMusicList();
        //避免重复添加音乐
        if(musicArrayList.isEmpty()){
            Cursor MusicCursor = getContentResolver().query(
                    MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                    new String[]{ MediaStore.Audio.Media.TITLE,
                            MediaStore.Audio.Media.DURATION,
                            MediaStore.Audio.Media.ALBUM,
                            MediaStore.Audio.Media.ARTIST,
                            MediaStore.Audio.Media._ID,
                            MediaStore.Audio.Media.DATA,
                            MediaStore.Audio.Media.DISPLAY_NAME
                    },null , null,
                    MediaStore.Audio.AudioColumns.TITLE);

            if(musicArrayList != null){
                //歌名，艺术家，总时长，路径
                int indexTitle = MusicCursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
                int indexArtist = MusicCursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);
                int indexTotalTime = MusicCursor.getColumnIndex(MediaStore.Audio.Media.DURATION);
                int indexPath = MusicCursor.getColumnIndex(MediaStore.Audio.Media.DATA);

                /**遍历数据库，将Music类对象加载到ArrayList中*/
                for(MusicCursor.moveToFirst(); !MusicCursor.isAfterLast(); MusicCursor.moveToNext()){
                    String strTitle = MusicCursor.getString(indexTitle);
                    String strArtist = MusicCursor.getString(indexArtist);
                    String strPath = MusicCursor.getString(indexPath);
                    String strTotalTime = MusicCursor.getString(indexTotalTime);

                    if(strArtist.equals("<unknown>"))
                        strArtist = "无艺术家";
                    Music music = new Music(strTitle,strArtist,strPath,strTotalTime);
                    musicArrayList.add(music);
                }
            }
        }
    }

    /**设置适配器并初始化ListView*/
    private void initListView(){
        List<Map<String, String>> list_map = new ArrayList<Map<String, String>>();
        HashMap<String, String> map;
        SimpleAdapter simpleAdapter;
        for(Music music : musicArrayList){
            map = new HashMap<String, String>();
            map.put("musicName", music.getMusicName());
            map.put("musicArtist", music.getMusicArtist());
            list_map.add(map);
        }

        String[] form = new String[]{ "musicName", "musicArtist"};
        int[] to = { R.id.listview_tv_title_item, R.id.listview_tv_artist_item};

        simpleAdapter = new SimpleAdapter(this, list_map, R.layout.listview, form, to);
        listView.setAdapter(simpleAdapter);
    }

    /** 检测有无有可播放音乐*/
    private void checkMusicfile(){
        if(musicArrayList.isEmpty()){
            imgBtn_Next.setEnabled(false);
            imgBtn_Pause.setEnabled(false);
            imgBtn_Previous.setEnabled(false);
            imgBtn_Stop.setEnabled(false);
            Toast.makeText(getApplicationContext(),"当前没有可以播放的音乐", Toast.LENGTH_LONG).show();
        }else {
            imgBtn_Next.setEnabled(true);
            imgBtn_Pause.setEnabled(true);
            imgBtn_Previous.setEnabled(true);
            imgBtn_Stop.setEnabled(true);
        }
    }

    /**Activity发送广播命令，控制音乐播放*/
    private void sendBroadcastOnCommand(int command){
        Intent intent = new Intent(MusicService.BROADCAST_MUSICSERVICE_CONTROL);
        intent.putExtra("command",command);
        //根据命令分装不同的数据
        switch (command) {
            case MusicService.COMMAND_PLAY :
                intent.putExtra("number", number);
                break;
            case MusicService.COMMAND_SEEK_TO :
                intent.putExtra("time", time);
                break;
            case MusicService.COMMAND_PAUSE :
            case MusicService.COMMAND_STOP :
            case MusicService.COMMAND_RESUME :
            case MusicService.COMMAND_PREVIOUS :
            case MusicService.COMMAND_NEXT :
            default:
                break;
        }
        sendBroadcast(intent);
    }

    /**更新UI*/
    class StatusChangReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            //获取播放器状态
            status = intent.getIntExtra("status", -1);
            String musicName = intent.getStringExtra("musicName");
            String musicArtist = intent.getStringExtra("musicArtist");
            switch (status){
                case MusicService.STATUS_PLAYING :
                    seekBarHandler.removeMessages(PROGRESS_INCREASE);
                    time = intent.getIntExtra("time", 0);
                    duration = intent.getIntExtra("duration", 0);
                    listView.setSelection(number);
                    seekBar.setProgress(time);
                    seekBar.setMax(duration);
                    seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE, 1000);
                    text_Duration.setText(formatTime(duration));
                    imgBtn_Pause.setImageResource(R.drawable.button_pause);
                    //设置Title的文字
                    MyPlayer.this.setTitle("正在播放" + musicName + " - " + musicArtist);
                    //设置textView的文字
                    textView.setText("正在播放" + musicName + " - " + musicArtist);
                    break;
                case MusicService.STATUS_PAUSED :
                    seekBarHandler.sendEmptyMessage(PROGRESS_PAUSE);
                    imgBtn_Pause.setImageResource(R.drawable.button_play);
                    String string = MyPlayer.this.getTitle().toString().replace("正在播放", "已暂停");
                    MyPlayer.this.setTitle(string);
                    textView.setText(string);
                    break;
                case MusicService.STATUS_STOPED :
                    time = 0;
                    duration = 0;
                    text_Current.setText(formatTime(time));
                    text_Duration.setText(formatTime(duration));
                    seekBarHandler.sendEmptyMessage(PROGRESS_RESET);
                    imgBtn_Pause.setImageResource(R.drawable.button_play);
                    MyPlayer.this.setTitle("MyPlayer");
                    textView.setText("");
                    break;
                case MusicService.STATUS_COMPLETED :
                    number = intent.getIntExtra("number", 0);
                    if(playmode == MyPlayer.MODE_LIST_SEQUENCE){//顺序播放
                        if(number == MusicList.getMusicList().size() - 1){
                            sendBroadcastOnCommand(MusicService.COMMAND_STOP);
                            MyPlayer.this.setTitle("MyPlayer");
                            textView.setText("");
                        }else{
                            sendBroadcastOnCommand(MusicService.COMMAND_NEXT);
                        }
                    }
                    else if(playmode == MyPlayer.MODE_SINGLE_CYCLE){//单曲循环
                        sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
                    }
                    else if(playmode == MyPlayer.MODE_LIST_CYCLE){//列表循环
                        if(number == MusicList.getMusicList().size() - 1){
                            number = 0;
                            sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
                        }else{
                            sendBroadcastOnCommand(MusicService.COMMAND_NEXT);
                        }
                    }
                    seekBarHandler.sendEmptyMessage(PROGRESS_RESET);
                    imgBtn_Pause.setImageResource(R.drawable.button_play);
                    break;
                default:
                    break;
            }
        }
    }

    /**格式化时间*/
    private String formatTime(int msec){
        int minute = msec / 1000 / 60;
        int second = msec / 1000 % 60;
        String minuteString;
        String secondString;
        if (minute < 10){
            minuteString = "0" + minute;
        }else{
            minuteString = "" + minute;
        }
        if (second < 10){
            secondString = "0" + second;
        }else{
            secondString = "" + second;
        }
        return minuteString + ":" + secondString;
    }

    /**控制进度条命令*/
    private void initseekBarHandler(){
        seekBarHandler =new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what){
                    case PROGRESS_INCREASE:
                        if(seekBar.getProgress() < duration){
                            //进度条前进1秒
                            seekBar.setProgress(time);
                            //seekBar.incrementProgressBy(1000);
                            seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE, 1000);
                            //修改显示当前进度的文本
                            text_Current.setText(formatTime(time));
                            time += 1000;
                        }
                        break;
                    case PROGRESS_PAUSE:
                        seekBarHandler.removeMessages(PROGRESS_INCREASE);
                        break;
                    case PROGRESS_RESET:
                        //重置进度条画面
                        seekBarHandler.removeMessages(PROGRESS_INCREASE);
                        seekBar.setProgress(0);
                        text_Current.setText("00:00");
                        break;
                }
            }
        };
    }

    /**设置Activity的主题，修改背景图片*/
    private void setTheme(String theme){
        if("彩色".equals(theme)){
            this.rootLayout.setBackgroundResource(R.drawable.bg_color);
        }
        if("花朵".equals(theme)){
            this.rootLayout.setBackgroundResource(R.drawable.bg_digit_flower);
        }
        if("群山".equals(theme)){
            this.rootLayout.setBackgroundResource(R.drawable.bg_mountain);
        }
        if("小狗".equals(theme)){
            this.rootLayout.setBackgroundResource(R.drawable.bg_running_dog);
        }
        if("冰雪".equals(theme)){
            this.rootLayout.setBackgroundResource(R.drawable.bg_snow);
        }
        if("女孩".equals(theme)){
            this.rootLayout.setBackgroundResource(R.drawable.bg_music_girl);
        }
        if("朦胧".equals(theme)){
            this.rootLayout.setBackgroundResource(R.drawable.bg_blur);
        }
    }

    /**创建菜单*/
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        this.getMenuInflater().inflate(R.menu.menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    /**处理菜单*/
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            //显示列表对话框
            case R.id.menu_theme:
                new AlertDialog.Builder(this)
                        .setTitle("请选择主题")
                        .setItems(R.array.theme,
                                new DialogInterface.OnClickListener(){
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        //获取在array.xml定义的主题名字
                                        String theme = PropertyBean.THEMES[which];
                                        //设置Acitvity的主题
                                        setTheme(theme);
                                        //保存主题
                                        PropertyBean property = new PropertyBean(MyPlayer.this);
                                        property.saveTheme(theme);
                                    }
                                }).show();
                break;
            case R.id.menu_playmode:
                String[] mode = new String[]{"顺序播放", "单曲循环", "列表循环"};
                AlertDialog.Builder builder = new AlertDialog.Builder(MyPlayer.this);
                builder.setTitle("播放模式");
                //设置单选项，第一个参数表示单选列表中要显示的数据,第二个参数是默认选择的项
                builder.setSingleChoiceItems(mode, playmode, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int arg1) {
                        playmode = arg1;
                    }
                });
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int arg1) {
                        switch (playmode){
                            case 0:
                                playmode = MyPlayer.MODE_LIST_SEQUENCE;
                                Toast.makeText(getApplicationContext(), R.string.sequence, Toast.LENGTH_SHORT).show();
                                break;
                            case 1:
                                playmode = MyPlayer.MODE_SINGLE_CYCLE;
                                Toast.makeText(getApplicationContext(), R.string.singlecycle, Toast.LENGTH_SHORT).show();
                                break;
                            case 2:
                                playmode = MyPlayer.MODE_LIST_CYCLE;
                                Toast.makeText(getApplicationContext(), R.string.listcycle, Toast.LENGTH_SHORT).show();
                                break;
                            default:
                                break;
                        }
                    }
                });
                builder.create().show();
                break;
            case R.id.menu_sleep:
                showSleepDialog();
                break;
            case R.id.menu_lrc:
                Intent intent = new Intent(MyPlayer.this, LrcActivity.class);
                startActivity(intent);
                break;
            case R.id.menu_about:
                //显示文本对话框
                new AlertDialog.Builder(MyPlayer.this).setTitle("MyPlayer")
                        .setMessage(R.string.about2).show();
                break;
            case R.id.menu_quit:
                //退出程序
                new AlertDialog.Builder(MyPlayer.this).setTitle("提示")
                        .setMessage(R.string.quit_message)
                        .setPositiveButton("确定",  new DialogInterface.OnClickListener(){
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                //System.exit(0);
                                Intent intent1 = new Intent(MyPlayer.this, MusicService.class);
                                stopService(intent1);
                                finish();
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener(){
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        }).show();
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    /**按键处理*/
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        int progress;
        switch (keyCode){
            case KeyEvent.KEYCODE_BACK:
                exitByDoubleClick();
                break;
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                progress = seekBar_vol.getProgress();
                if(progress != 0){
                    seekBar_vol.setProgress(progress-1);
                }
                return true;
            case KeyEvent.KEYCODE_VOLUME_UP:
                progress = seekBar_vol.getProgress();
                if(progress != 0){
                    seekBar_vol.setProgress(progress+1);
                }
                return true;
            default:
                break;
        }
        return false;
    }

    private void exitByDoubleClick(){
        Timer timer = null;
        if(isExit == false){
            isExit = true;//准备退出
            Toast.makeText(this, R.string.msg_exit, Toast.LENGTH_SHORT).show();
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false;
                }
            }, 2000);
        }else{
            //System.exit(0);
            Intent intent1 = new Intent(MyPlayer.this, MusicService.class);
            stopService(intent1);
            finish();
        }
    }

    /**音量控制*/
    private void audio_Control(){
        //获取音量管理器
        final AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        //设置只针对媒体音量的音量大小
        this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
        //设置滑动条最大值
        final int max_progress = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        //获取当前音量
        int progress = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        seekBar_vol.setProgress(progress);
        tv_vol.setText("音量：" + (progress*100/max_progress) + "%");
        seekBar_vol.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                tv_vol.setText("音量：" + (progress*100/max_progress) + "%");
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, progress, AudioManager.FLAG_PLAY_SOUND);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }

    /**睡眠设置处理*/
    private void showSleepDialog() {
        //获取布局，初始化一个View对象
        final View userView = this.getLayoutInflater().inflate(R.layout.dialog, null);
        //通过View类findViewById()方法的获取组件
        final TextView tv_minute = (TextView) userView.findViewById(R.id.dialog_tv);
        final Switch switch1 = (Switch) userView.findViewById(R.id.dialog_switch);
        final SeekBar seekBar = (SeekBar) userView.findViewById(R.id.dialog_seekBar);

        tv_minute.setText("睡眠于：" + sleep_minute + "分钟");
        //根据当前睡眠状态设置switch状态
        if(sleepmode == MyPlayer.ISTSLEEP) switch1.setChecked(true);
        seekBar.setMax(60);
        seekBar.setProgress(sleep_minute);
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                sleep_minute = progress;
                tv_minute.setText("睡眠于：" + sleep_minute + "分钟");
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                sleepmode = isChecked;
            }
        });
        //定义定时器任务
        final TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                //System.exit(0);
                Intent intent1 = new Intent(MyPlayer.this, MusicService.class);
                stopService(intent1);
                finish();
            }
        };
        //定义对话框以及初始化
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setTitle("选择睡眠时间(0~60分钟)");
        //设置布局
        dialog.setView(userView);
        //设置取消按钮响应事件
        dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        //设置重置按钮响应事件
        dialog.setNeutralButton("重置", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if(sleepmode == MyPlayer.ISTSLEEP){
                    timerTask.cancel();
                    timer_sleep.cancel();
                }
                sleepmode = MyPlayer.NOTSLEEP;
                sleep_minute = 20;
                iv_sleep.setVisibility(View.INVISIBLE);
            }
        });
        //设置确定按钮响应事件
        dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if(sleepmode == MyPlayer.ISTSLEEP){
                    timer_sleep = new Timer();
                    int time = seekBar.getProgress();
                    //启动任务
                    timer_sleep.schedule(timerTask, time*60*1000);
                }else{
                    //取消任务
                    timerTask.cancel();
                    if(timer_sleep != null) timer_sleep.cancel();
                    dialog.dismiss();
                    iv_sleep.setVisibility(View.INVISIBLE);
                }
            }
        });
        dialog.show();
    }

    /**
    ***      触摸控制
    */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return gestureDetector.onTouchEvent(event);
    }

    @Override
    public boolean onDown(MotionEvent e) {
        return false;
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        if(e1.getX() - e2.getX() > 150)//终点与起点的横坐标之差是否大于150像素
        {
            Intent intent = new Intent();
            intent.setClass(MyPlayer.this, LrcActivity.class);
            startActivity(intent);
            //实现了两个Activity切换时的动画
            overridePendingTransition(R.anim.to_right_enter, R.anim.to_right_exit);
            Toast.makeText(getApplicationContext(), "歌词", Toast.LENGTH_SHORT).show();
        }
        return false;
    }

    @Override
    public void onLongPress(MotionEvent e) {

    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        return false;
    }

    @Override
    public void onShowPress(MotionEvent e) {

    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        return false;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if(gestureDetector.onTouchEvent(ev)) //优先响应顶层VIEW的触屏事件
        {
            ev.setAction(MotionEvent.ACTION_CANCEL);
        }
        return super.dispatchTouchEvent(ev);
    }
}
